package org.example;

import com.alibaba.fastjson.JSONObject;

import javax.persistence.EntityManager;
import javax.persistence.EntityManagerFactory;
import javax.persistence.Persistence;
import javax.persistence.Query;
import java.util.Arrays;
import java.util.List;

/**
 * Hello world!
 */
public class App {
    public static void main(String[] args) {
        EntityManagerFactory emf = Persistence.createEntityManagerFactory("my-persistence-unit");
        EntityManager em = emf.createEntityManager();
        nativeQuery(em,"SHOW TABLES");
        nativeQuery(em,"SHOW COLUMNS FROM CUSTOMER");
        nativeQuery(em,"SHOW COLUMNS FROM ORDERITEM");
        persistEntity(em);
        loadEntities(em);
        em.close();
        emf.close();
    }
    private static void loadEntities(EntityManager em){
        Query query = em.createQuery("select c from Customer c");
        List<Customer> customers = query.getResultList();
        customers.forEach(System.err::println);
        for (Customer customer : customers) {
            OrderItem orderItem = customer.getOrderItem();
            System.err.println(orderItem);
        }
    }
    private static void persistEntity(EntityManager em){
        Customer customer = new Customer();
        customer.setName("Maria Dorsey");
        customer.setAddress("1719 Shumaker Boulevard, Sylvania");
        OrderItem orderItem = new OrderItem("GEN SSD",2);
        customer.setOrderItem(orderItem);
        em.getTransaction().begin();
        em.persist(customer);
        em.persist(orderItem);
        em.getTransaction().commit();
    }
    private static void nativeQuery(EntityManager em,String s){
        System.err.println("---------" + s + "-------------");
        Query query = em.createNativeQuery(s);
        List<Object[]> list = query.getResultList();
        for (Object[] objects : list) {
            System.err.println(Arrays.toString(objects));
        }
    }
}
